//
//  HBAudioPlayController.m
//  HappyBaby
//
//  Created by lanou on 15/11/28.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "HBAudioPlayController.h"
#import <Masonry.h>
#import "HBAudioPlayControlView.h"
#import "HBAudioTool.h"
#import "ChildrenStoryInterface.h"
#import "UIImageView+WebCache.h"
//#import <MediaPlayer/MediaPlayer.h>

@interface HBAudioPlayController ()<HBAudioPlayDelegate>

/** 背景转盘imageView */
@property (weak, nonatomic) UIImageView *musicImageView;

/** 控制条View */
@property (nonatomic, weak) UIImageView *controlImageView;

/** 中间图片 */
@property (nonatomic, weak) UIImageView *picImageView;

/** 流媒体播放音频 */
@property (strong, nonatomic) MPMoviePlayerController *moviePlayer;

/** 底部View */
@property (nonatomic, weak) HBAudioPlayControlView *controlView;

/** timer定时器 */
@property (strong, nonatomic) NSTimer *timer;

@end

@implementation HBAudioPlayController
{
    BOOL _isPlaying;
}


- (void)dealloc
{
    // 移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMovieDurationAvailableNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:nil];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 背景颜色
    self.view.backgroundColor = [UIColor colorWithRed:169/255.0 green:110/255.0 blue:127/255.0 alpha:1.0];
    
   UIButton *button = self.navigationItem.leftBarButtonItem.customView;
    [button addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    // 1.初始化View
    [self makeView];
    
    // 2.动画显示
    [self animationImageView];
    
    // 3.底部控制View初始化
    [self setUpBottomControlView];
    
    // 4.播放音乐
    ChildrenStoryInterface *detailModel = self.musicArray[_playIndex];
    MPMoviePlayerController *moviePlayer = [HBAudioTool playMusic:detailModel.downurl];
    // 必须设置该播放器的View尺寸，否则会出现约束错误
    [self.view addSubview:moviePlayer.view];
    moviePlayer.view.hidden = YES;
    moviePlayer.view.bounds = self.view.bounds;
    self.moviePlayer = moviePlayer;
    
    // 添加音频流加载完成后的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(durationAvailable) name:MPMovieDurationAvailableNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackDidFinish) name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}

#pragma mark 点击按钮返回前一个界面
- (void)backBtnClick:(UIButton *)btn
{
    ChildrenStoryInterface *detailModel = self.musicArray[_playIndex];
    [HBAudioTool stopMusic:detailModel.downurl];
    
    // 停止定时器
    [self.timer invalidate];
    self.timer = nil;
}

#pragma mark timer定时器更新事件
- (void)timerUpdate
{
    self.controlView.playingTime = self.moviePlayer.currentPlaybackTime;
}

#pragma mark 音频播放完成通知
- (void)playbackDidFinish
{
    [self handleMusicPlay];
}

#pragma mark 音频流加载完成通知
- (void)durationAvailable
{
    self.controlView.duration = self.moviePlayer.duration;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES];
}

#pragma mark 底部控制条View
- (void)setUpBottomControlView
{
    __weak typeof(self) weakSelf = self;
    
    HBAudioPlayControlView *controlView = [[HBAudioPlayControlView alloc]init];
    controlView.delegate = self;
    [self.view addSubview:controlView];
    self.controlView = controlView;
    
    [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view).with.offset(-30);
        make.height.equalTo(weakSelf.view).with.multipliedBy(0.15);
    }];
}

#pragma mark 暂停动画
- (void)pauseLayer:(CALayer *)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
    
    // 暂停动画的时候 改变控制条
    self.controlImageView.transform = CGAffineTransformMakeRotation(-M_PI / 18);
}

#pragma mark 继续动画
- (void)resumeLayer:(CALayer *)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
    
    // 恢复控制条偏移角度
    self.controlImageView.transform = CGAffineTransformIdentity;
}

#pragma mark 动画制作
- (void)animationImageView
{
    CABasicAnimation *baseicAnimation = [CABasicAnimation animation];
    baseicAnimation.keyPath = @"transform.rotation";
    baseicAnimation.toValue = @(M_PI);
    baseicAnimation.duration = 8;
    baseicAnimation.repeatCount = MAXFLOAT;
    
    baseicAnimation.removedOnCompletion = NO;
    baseicAnimation.fillMode = kCAFillModeForwards;
    baseicAnimation.cumulative = YES;

    [self.musicImageView.layer addAnimation:baseicAnimation forKey:@"musicImageView"];
}

#pragma mark 初始化View
- (void)makeView
{
    // 1.图片显示
    UIImageView *musicImageView = [UIImageView new];
    musicImageView.image = [UIImage imageNamed:@"icn_play_disc"];
    [self.view addSubview:musicImageView];
    self.musicImageView = musicImageView;

    // 中间转盘的图片显示
    UIImageView *picImageView = [UIImageView new];
    picImageView.clipsToBounds = YES;
    picImageView.image = [UIImage imageNamed:@"Jay"];
    [musicImageView addSubview:picImageView];
    self.picImageView = picImageView;
    
    // 播放音乐
    ChildrenStoryInterface *detailModel = self.musicArray[_playIndex];
    [HBAudioTool playMusic:detailModel.downurl];
    [picImageView sd_setImageWithURL:[NSURL URLWithString:detailModel.pic] placeholderImage:[UIImage imageNamed:@"Jay"]];
    
    UIImageView *controlImageView = [UIImageView new];
    controlImageView.image = [UIImage imageNamed:@"icn_play_needle"];
    [self.view addSubview:controlImageView];
    self.controlImageView = controlImageView;
    
    // 2.添加约束
    __weak typeof(self) weakSelf = self;
    [musicImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view);
        make.centerY.equalTo(weakSelf.view).with.offset(-40);
        make.width.and.height.equalTo(weakSelf.view.mas_width).multipliedBy(0.6);
    }];
    
    [picImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(musicImageView);
        make.width.and.height.equalTo(musicImageView).multipliedBy(0.66);
    }];
    
    [controlImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view).with.offset(-weakSelf.view.frame.size.width * 0.3);
        make.centerX.equalTo(weakSelf.view);
        make.width.equalTo(weakSelf.view).multipliedBy(0.45);
        make.height.equalTo(weakSelf.view).multipliedBy(0.35);
    }];
    // 计算半径 0.18 = 0.6 * 0.6 * 0.5
    CGFloat cornerRadius = self.view.frame.size.width * 0.6 * 0.66 * 0.5;
    picImageView.layer.cornerRadius = cornerRadius;
    
    controlImageView.layer.anchorPoint = CGPointMake(0.5, 0);
}


#pragma mark 控制View代理方法
- (void)audioPlayBtnClick:(HBAudioPlayControlView *)audioPlay buttonIndex:(AudioPlayIndex)audioPlayIndex
{
    switch (audioPlayIndex) {
        case MiddleBtnIndex:
            [self handleMusicPlay];// 处理播放事件
            break;
        case LeftBtnIndex:
            [self handlePreviousMusic]; // 处理播放前一首
            break;
        case RightBtnIndex:
            break;
        default:
            break;
    }
}

#pragma mark 处理播放前一首播放事件
- (void)handlePreviousMusic
{
    // 首先销毁当前的播放
    ChildrenStoryInterface *detailModel = self.musicArray[_playIndex];
    [HBAudioTool stopMusic:detailModel.downurl];
    
    _playIndex --;
    if (_playIndex < 0) {
        _playIndex = 0;
        
        // 提示当前已经是第一首歌曲
    }
    
    // 新建播放
    detailModel = self.musicArray[_playIndex];
    [HBAudioTool playMusic:detailModel.downurl];
    [self.picImageView sd_setImageWithURL:[NSURL URLWithString:detailModel.pic] placeholderImage:[UIImage imageNamed:@"Jay"]];
    
}

#pragma mark 处理当前播放事件
- (void)handleMusicPlay
{
    ChildrenStoryInterface *detailModel = self.musicArray[_playIndex];
    if (!_isPlaying) {
        [HBAudioTool pauseMusic:detailModel.downurl];
        // 暂停动画
        [self pauseLayer:_musicImageView.layer];
    } else {
        [HBAudioTool playMusic:detailModel.downurl];
        // 继续动画
        [self resumeLayer:self.musicImageView.layer];
    }
    _isPlaying = !_isPlaying;
    self.controlView.isPlaying = _isPlaying;
}

@end
